package com.spring.springboot.configure;

import java.util.Map;

import javax.persistence.EntityManager;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
*@author LSY
*Time: 2018年12月18日下午5:25:29
*
*
*/
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
		entityManagerFactoryRef = "entityManagerFactoryUser2",
		transactionManagerRef = "transactionManagerUser2",
		basePackages = {"com.spring.springboot.user2"}
		)
public class User2DataSourceConfigurer {

	@Autowired
	@Qualifier("user2DataSource")
	private DataSource user2DataSource;
	
	@Bean("entityManagerUser2")
	public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
		return entityManagerFactoryUser2(builder).getObject().createEntityManager();
	}
	
	@Bean("entityManagerFactoryUser2")
	public LocalContainerEntityManagerFactoryBean entityManagerFactoryUser2(EntityManagerFactoryBuilder builder) {
		return builder
				.dataSource(user2DataSource)
				.properties(getVendorProperties())
				.packages(new String("com.spring.springboot.user2"))
				.persistenceUnit("user2PersistenceUnit")
				.build();
	}
	
	@Autowired
	private JpaProperties jpaProperties;
	private Map<String, Object> getVendorProperties() {
		return jpaProperties.getHibernateProperties(new HibernateSettings());
	}
	
	@Bean(name = "transactionManagerUser2")
	public PlatformTransactionManager transactionManagerUser2(EntityManagerFactoryBuilder builder) {
		return new JpaTransactionManager(entityManagerFactoryUser2(builder).getObject());
	}
}
